import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import { prisma } from "@/lib/prisma";

// 获取聊天的所有消息
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;

    // 检查聊天是否存在
    const chat = await prisma.chat.findUnique({
      where: { id },
      include: {
        knowledgeBase: true,
      },
    });

    if (!chat) {
      return NextResponse.json(
        { success: false, error: "聊天不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的聊天
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || chat.knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此聊天" },
        { status: 403 }
      );
    }

    // 获取聊天消息
    const messages = await prisma.message.findMany({
      where: { chatId: id },
      orderBy: { createdAt: "asc" },
    });

    return NextResponse.json({
      success: true,
      data: messages,
    });
  } catch (error) {
    console.error("获取聊天消息失败:", error);
    return NextResponse.json(
      { success: false, error: "获取聊天消息失败" },
      { status: 500 }
    );
  }
}

// 创建新消息
export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;
    const body = await req.json();
    const { content, role } = body;

    // 验证请求数据
    if (!content || typeof content !== "string") {
      return NextResponse.json(
        { success: false, error: "消息内容是必填项" },
        { status: 400 }
      );
    }

    if (!role || !["user", "assistant"].includes(role)) {
      return NextResponse.json(
        { success: false, error: "角色必须是 'user' 或 'assistant'" },
        { status: 400 }
      );
    }

    // 检查聊天是否存在
    const chat = await prisma.chat.findUnique({
      where: { id },
      include: {
        knowledgeBase: true,
      },
    });

    if (!chat) {
      return NextResponse.json(
        { success: false, error: "聊天不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的聊天
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || chat.knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此聊天" },
        { status: 403 }
      );
    }

    // 创建新消息
    const message = await prisma.message.create({
      data: {
        content,
        role,
        chatId: id,
      },
    });

    return NextResponse.json({
      success: true,
      data: message,
    });
  } catch (error) {
    console.error("创建消息失败:", error);
    return NextResponse.json(
      { success: false, error: "创建消息失败" },
      { status: 500 }
    );
  }
} 